﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;
using System.IO;
using System.Threading;
using System.ComponentModel;
using CustomProgressBar;
using ActivityTracker.Library;
using CommonControls.ClassFiles;

namespace ActivityTracker
{
    public partial class MediaPlayer : PhoneApplicationPage
    {
        string keyName = "";
        public static string VideoFolder;
        public static string VideoFile;
        IsolatedStorageFileStream destStream = null;
        private ProgressIndicator progress;
        public MediaPlayer()
        {
            InitializeComponent();
            Application.Current.Host.Settings.EnableFrameRateCounter = true;
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (this.progress == null)
            {
                this.progress = new ProgressIndicator();
            }
            NavigationContext.QueryString.TryGetValue("key", out keyName);
            VideoHelp(keyName);
        }

        void VideoHelp(string enumkey)
        {
            try
            {
                //videolinks from our lartsoft account
                StringEnum se = new StringEnum(typeof(VideoLinks));
                VideoFile = se.GetStringValue(enumkey);
                VideoFolder = "http://athelpvideos.lartsoft.com/";

                using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (!storage.FileExists(VideoFile))
                    {
                        progress.Show();
                        WebClient client = new WebClient();
                        client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                        client.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
                        client.OpenReadAsync(new Uri(VideoFolder + VideoFile, UriKind.Absolute));
                    }
                    else
                    {
                        destStream = storage.OpenFile(VideoFile, FileMode.Open);
                        MediaElement.SetSource(destStream);
                        MediaElement.Play();
                    }
                }
            }
            catch (Exception ex)
            {
                string message = "Exception playing help video for " + enumkey + "\n\n Stack Trace :- \n" + ex.StackTrace;
                ex.Data.Add("enumkey", enumkey);
                Exceptions.SaveOrSendExceptions(message, ex.Data);
            }
        }

        void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            if (e.TotalBytesToReceive != -1)
            {
                //progress.Show();
                progress.Text = (e.BytesReceived * 100 / e.TotalBytesToReceive).ToString() + "% Completed";
            }
        }

        void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            progress.Hide();
            if (e.Error == null)
            {
                using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (!storage.FileExists(VideoFile))
                    {
                        destStream = storage.CreateFile(VideoFile);
                        using (Stream sourceStream = e.Result)
                        {
                            // allocate a 500kb buffer to copy the file 
                            byte[] buffer = new byte[1024 * 500];
                            int bytesRead = 0;
                            int offset = 0;
                            while ((bytesRead = sourceStream.Read(buffer, offset, buffer.Length)) > 0)
                            {
                                destStream.Write(buffer, 0, bytesRead);
                            }
                        }
                        MediaElement.SetSource(destStream);
                        MediaElement.Play();
                    }
                }
            }
        }

        private void MediaElement_MediaFailed(object sender, ExceptionRoutedEventArgs e)
        {

        }

        protected override void OnBackKeyPress(CancelEventArgs e)
        {
            if (this.progress != null)
            {
                progress.Hide();
            }
        }
    }
}